package cn.com.analyze;
import java.text.DecimalFormat;
import java.util.HashMap;

import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.format.FormatUtils;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Tcp;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class AverageHandshakeTime {
	double sum = 0;
	int count = 0;
	HashMap<Integer, Double> waitlist = new HashMap<Integer, Double>();
	
	Context c;
	String hostip;
	
	public AverageHandshakeTime(Context context)
	{
		c = context;
		SharedPreferences mSharedPreferences = c.getSharedPreferences("hostip", Activity.MODE_PRIVATE);
		hostip = mSharedPreferences.getString("hostip", "");
	}
	
	public double getAverageHandshakeTime()
	{
		if(count == 0)
			return 0;
		double r = sum / count;
		DecimalFormat df = new DecimalFormat("0.000000");
		return Double.parseDouble(df.format(r));
	}
	
	private void update(double timeinter)
	{
		sum += timeinter;
		count ++;
	}
	
	Ip4 ip4 = new Ip4();
	Tcp tcp = new Tcp();
	int port;
	double start;
	double end;
	String src;
	public void add(JPacket packet)
	{
		if(packet.hasHeader(ip4))
		{
			packet.getHeader(ip4);
			src = FormatUtils.ip(ip4.source());
			if(!src.equals(hostip))
				return;
		}
		if(packet.hasHeader(tcp.ID))
		{
			packet.getHeader(tcp);
			if(tcp.flags_SYN())
			{
				port = tcp.destination();
				if(waitlist.containsKey(port))
				{
					return;
				}
				else
				{
					start = packet.getCaptureHeader().seconds() + (packet.getCaptureHeader().nanos() + 0.0) / (10.0E9);
					waitlist.put(port, start);
				}
			}
			else if(tcp.flags_ACK())
			{
				port = tcp.destination();
				if(waitlist.containsKey(port))
				{
					end = packet.getCaptureHeader().seconds() + (packet.getCaptureHeader().nanos() + 0.0) / (10.0E9);
					update(end - start);
					waitlist.remove(port);
				}
			}
		}
	}

}
